package com.holiday.springboot2.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.holiday.springboot2.domain.User;
import com.holiday.springboot2.service.impl.UserServiceImpl;
import com.holiday.springboot2.utils.JsonData;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//@WebFilter(urlPatterns = "/api/v1/pri/*", filterName = "LoginFilter")
public class LoginFilter implements Filter {


    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        System.out.println("容器 初始化执行");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //  核心逻辑
        System.out.println("核心逻辑");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // token会放在参数中，或者请求头中
        String token = req.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            //如果请求头获取不到token，则从参数中获取
            token = req.getParameter("token");
        }
        if (!StringUtils.isEmpty(token)) {

            // 最后不为空，则判断token是否合法
            User user = UserServiceImpl.sessionMap.get(token);
            if (user != null) {
                // 最后确认user为合法的,则放行
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                JsonData jsonData = JsonData.buildError("登录失败，token无效");
                // 将对象转为字符串
                String jsonStr = objectMapper.writeValueAsString(jsonData);
                try {
                    rederJson(resp,jsonStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }else {
            // 如果检验非法，则返回内容告诉前端
            JsonData jsonData = JsonData.buildError("未登录");
            // 将对象转为字符串
            String jsonStr = objectMapper.writeValueAsString(jsonData);
            try {
                rederJson(resp,jsonStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }




    }

    private void rederJson(HttpServletResponse response, String json) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        // 将json内容返回给前端
        writer.print(json);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        System.out.println("容器销毁执行");
    }
}
